package com.party.core.service.crowdfund.biz;

import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.activity.Activity;
import com.party.core.model.crowdfund.Project;
import com.party.core.model.crowdfund.ProjectWithAuthor;
import com.party.core.model.crowdfund.SupportStatus;
import com.party.core.service.activity.IActivityService;
import com.party.core.service.crowdfund.IProjectService;
import com.party.core.service.crowdfund.ISupportService;
import com.party.core.service.order.IOrderFormService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @Description:
 * @Author: yangshoukun
 * @Date: 2018/6/14 14:27
 */
@Service
public class CrowdfundReviseBizService {
    @Autowired
    private IProjectService projectService;

    @Autowired
    private ISupportService supportService;

    @Autowired
    private IOrderFormService orderFormService;

    @Autowired
    private IActivityService activityService;

    protected static Logger logger = LoggerFactory.getLogger(CrowdfundReviseBizService.class);

    private void reviseProject(Project param, boolean all) {
        List<Project> projectList = projectService.list(param);
        for (Project project : projectList) {
            //过滤掉已经筹满的
            if (!all && project.getIsSuccess().equals(Constant.CROWDFUND_PROJECT_SUCCESS)) {
                continue;
            }
            this.reviseProjectData(project);
        }
    }


    /**
     * @param project 众筹
     * @return
     * @Author yifeng
     * @Description 更新众筹数据
     * @Date 14:12 2019/4/12
     **/
    public void reviseProjectData(Project project) {
//        List<String> notMatchSupportIdsPay = supportService.getStatusNotMatchSupport(project.getId(),
//                OrderStatus.ORDER_STATUS_HAVE_PAID.getCode(), 1);
//        supportService.batchUpdate(notMatchSupportIdsPay, 1);
//
//        List<String> notMatchSupportIdsRefund = supportService.getStatusNotMatchSupport(project.getId(),
//                OrderStatus.ORDER_STATUS_REFUND.getCode(), 3);
//        supportService.batchUpdate(notMatchSupportIdsRefund, 3);

        Project dbProject = projectService.getSupportMoneyAndCount(project.getId());
        project.setFavorerNum(dbProject.getFavorerNum());

        Float realAmount = dbProject.getRealTimeAmount();
        project.setRealTimeAmount(realAmount);
        project.setActualAmount(realAmount > project.getTargetAmount() ? project.getTargetAmount() : realAmount);
        if (realAmount >= project.getTargetAmount()) {
            //众筹成功
            project.setIsSuccess(Constant.CROWDFUND_PROJECT_SUCCESS);
        } else if (new Float(0.0f).equals(project.getActualAmount())) {
            List<Integer> statusList = supportService.getStatusByProjectId(project.getId());
            if (statusList.size() == 1 && SupportStatus.REFUND_SUCCESS.getCode().equals(statusList.get(0))) {
                // 退款成功
                project.setIsSuccess(Constant.CROWDFUND_PROJECT_REFUNDED);
            } else {
                // 众筹中
                project.setIsSuccess(Constant.IS_CROWFUND_ING);
            }
        } else {
            // 众筹中
            project.setIsSuccess(Constant.IS_CROWFUND_ING);
        }
        projectService.update(project);
    }


    private void reviseTarget(Activity activity) {
        activity.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        activity.setIsCrowdfunded(Constant.IS_CROWDFUNDED);

        List<Activity> list = activityService.list(activity);

        for (Activity a : list) {
            reviseTargetData(a);
        }
    }

    /**
     * @param activity 项目
     * @return
     * @Author yifeng
     * @Description 校正项目数据
     * @Date 14:28 2019/4/12
     **/
    public void reviseTargetData(Activity activity) {
        if (YesNoStatus.NO.getCode().equals(activity.getIsMultiple())) {
            Activity dbActivity = activityService.getZcNumByTargetId(activity.getId(), true);

            activity.setBeCrowdfundNum(dbActivity.getBeCrowdfundNum());
            activity.setCrowdfundedNum(dbActivity.getCrowdfundedNum());
            activity.setJoinNum(dbActivity.getJoinNum());
        }
        if (YesNoStatus.YES.getCode().equals(activity.getIsMultiple())) {
            // todo 多场活动的众筹人数校正查询要优化
            ProjectWithAuthor projectWithAuthor = new ProjectWithAuthor();
            //众筹成功
            projectWithAuthor.setIsSuccess(1);
            projectWithAuthor.setTargetId(activity.getId());

            List<ProjectWithAuthor> crowfunded = projectService.gradationListWithAuthorPage(projectWithAuthor, null);
            //众筹中
            projectWithAuthor.setIsSuccess(0);
            List<ProjectWithAuthor> beCrowfund = projectService.gradationListWithAuthorPage(projectWithAuthor, null);
            activity.setBeCrowdfundNum(beCrowfund.size());
            activity.setCrowdfundedNum(crowfunded.size());

            Activity dbActivity = activityService.getZcNumByTargetId(activity.getId(), false);
            activity.setJoinNum(dbActivity.getJoinNum());
        }

        Integer favorerNum = supportService.countByTargetId(activity.getId(), Constant.SUPPORT_PAY_STATUS_SUCCESS,
                Constant.SUPPORT_PAY_STATUS_FAIL);
        Map<String, Object> activityData = orderFormService.statisticZcActivityData(activity.getId());
        Long orderNum = activityData.get("orderNum") != null ? (Long) activityData.get("orderNum") : 0L;
        Double totalMoney = activityData.get("totalMoney") != null ? (Double) activityData.get("totalMoney") : 0d;
        activity.setOrderNum(orderNum);
        activity.setTotalMoney(totalMoney);
        activity.setFavorerNum(favorerNum);
        activityService.update(activity);
    }


    /**
     * 矫正所有众筹
     */
    public void revise() {
        reviseProject(new Project(), false);
    }

    /**
     * 矫正所有众筹活动
     */
    public void targetRevise() {
        reviseTarget(new Activity());
    }

    /**
     * 矫正一个众筹的数据
     * @param projectId
     */
    public void reviseOne(String projectId) {
        if (StringUtils.isEmpty(projectId)) {
            return;
        }
        Project project = new Project();
        project.setId(projectId);
        reviseProject(project, true);
    }

    /**
     * 矫正一个众筹项目的数据
     * @param activityId
     */
    public void targetReviseOne(String activityId) {
        if (StringUtils.isEmpty(activityId)) {
            return;
        }
        Activity activity = new Activity();
        activity.setId(activityId);
        reviseTarget(activity);
    }
}
